<!-- views/auth/StudentLogin.vue -->
<template>
  <div class="login-page">
    <div class="login-header">
      <h2>学生登录</h2>
      <p>请输入您的学号和密码</p>
    </div>

    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" class="login-form">
      <el-form-item label="学号" prop="studentId">
        <el-input v-model="form.studentId" placeholder="请输入学号" clearable prefix-icon="User" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password prefix-icon="Lock" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleLogin" :loading="loading">
          登录
        </el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="text" @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>

    <div class="login-footer">
      <p>初始密码为123456，登录后请修改</p>
      <p>技术支持：计算机与信息学院</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        studentId: '',
        password: ''
      },
      rules: {
        studentId: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { min: 6, max: 20, message: '学号长度为6-20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
        ]
      },
      loading: false
    };
  },
  methods: {
    /**
     * 处理登录
     */
    async handleLogin() {
      // 1. 表单验证
      try {
        await this.$refs.formRef.validate();
      } catch (err) {
        return;
      }

      try {
        // 2. 设置加载状态
        this.loading = true;

        // 3. 调用登录API
        const token = await $authAPI.login({
          username: this.form.studentId,
          password: this.form.password,
          role: 'student'
        });

        // 4. 保存Token
        localStorage.setItem('token', token);

        // 5. 设置用户信息
        $userStore.setUser(this.form.studentId, 'STUDENT');

        // 6. 跳转到首页
        this.$message.success('登录成功');
        this.$router.push('/student');
      } catch (err) {
        // 7. 错误处理
        this.$message.error(err.message || '登录失败');
      } finally {
        // 8. 重置加载状态
        this.loading = false;
      }
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.$refs.formRef.resetFields();
    },

    /**
     * 返回上一页
     */
    goBack() {
      this.$router.push('/login');
    }
  }
};
</script>